package com.horay.springbootdemo.transactional;

import com.horay.springbootdemo.common.model.Foo;
import com.horay.springbootdemo.transactional.service.FooService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * 服务启动类
 *
 * @author heyingcheng
 * @date 2019/11/6 22:12
 */
@Slf4j
@SpringBootApplication
public class TransactionalApplication implements CommandLineRunner {

    @Autowired
    private FooService fooService;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public static void main(String[] args) {
        SpringApplication.run(TransactionalApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        fooService.insert();
        log.info("count:[{}]", count());

        try {
            fooService.insertThenRollback();
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("count:[{}]", count());

        try {
            fooService.invokeInsertThenRollback();
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("count:[{}]", count());
    }

    public long count() {
        return jdbcTemplate.queryForObject(Foo.SELECT_COUNT_SQL, Long.class);
    }

}
